package sg.edu.nus.iss.cats.util;

import javax.servlet.ServletException;
import org.apache.commons.beanutils.*;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.config.ModuleConfig;

/*
 * This class does nothing except initialize the Date converters for the
 * BeanUtils utilities that transfer data between form beans and DTOs.
 * The initialize() method should be invoked in classes that use dates in the
 * forms.
 * We'll have a smarter way of doing this later.
 */
public class ConvertersPlugIn implements org.apache.struts.action.PlugIn {


    /**
      * Name of application attribute under which the .
      */
	public static final String DATE_FORMAT_ATTRIBUTE = "APPL_DATE_FORMAT";

    /**
      * Register the Date-to-String and String-to-Date converters,
      * (they are in package sg.edu.nus.iss.cats.util).
      * These are used by BeanUtils.copyProperties() method to
      * convert between java.util.Date and String.
      *
      * This class is implemented as a Struts PlugIn so that it
      * is automatically loaded at startup and the desired
      * date format can be specified in the plugin initialization
      * parameter "dateFormat".
      */
    private String dateFormat = null;

    public void setDateFormat (String dateFormat) {
		this.dateFormat = dateFormat;
	}

    public String getDateFormat () {
		return dateFormat;
	}

    public void init (ActionServlet servlet, ModuleConfig config)
                                                throws ServletException {
        System.out.println("Starting converters registration");

        StringToDateBeanUtilsConverter dateConverter = null;
        DateToStringBeanUtilsConverter stringConverter = null;

        dateConverter = new StringToDateBeanUtilsConverter();
        stringConverter = new DateToStringBeanUtilsConverter();

        if (dateFormat == null) {
			throw new ServletException ("ConvertersPlugIn: dateFormat was not specified");
		}

        dateConverter.setFormatPattern (dateFormat);
        stringConverter.setFormatPattern (dateFormat);

        ConvertUtils.register (dateConverter, java.util.Date.class);
        ConvertUtils.register (stringConverter, String.class);

        servlet.getServletContext().setAttribute (DATE_FORMAT_ATTRIBUTE, dateFormat);

        System.out.println("Registered converters");
	}

    public void destroy () {
	}

}
